<template>
  <div class="wrapper">
    <van-nav-bar safe-area-inset-top placeholder>
      <template #title>
        <van-col>
          <van-icon name="points" size="20" color="red" />
        </van-col>
        <van-col>刻印搭配</van-col>
      </template>
    </van-nav-bar>

    <!-- 配置选项 -->
    <van-collapse accordion v-model="activeNames" @change="onCollapseChange">
      <!-- 套装设置 -->
      <van-collapse-item title="套装设置" name="1">
        <template #title>
          <div>
            <van-icon name="award" />&nbsp;套装设置
          </div>
        </template>

        <van-cell-group>
          <van-cell center>
            <template #right-icon>
              <van-switch v-model="setGroupNumCheck1" size="24" />
            </template>
            <template #title>
              <span :style="{ color: (setGroupNumCheck1 ? '#1989fa' : '#323233') }">1.两套刻印(3+3) 适合非Ω角色</span>
            </template>
          </van-cell>

          <van-cell center>
            <template #right-icon>
              <van-switch v-model="setGroupNumCheck2" size="24" />
            </template>
            <template #title>
              <span :style="{ color: (setGroupNumCheck2 ? '#1989fa' : '#323233') }">2.三套刻印(2+2+2) 适合Ω角色</span>
            </template>
          </van-cell>
        </van-cell-group>

        <van-row class="setting-img-margintop">
          <van-col span="4" offset="2" @click="onClickEngr(0)">
            <van-image width="60" height="60" :src="selectEngrIcon[0]" :show-error="true" :alt="'点击选择'" />
            <van-icon name="arrow-down" />
          </van-col>

          <van-col span="4" offset="4" @click="onClickEngr(1)">
            <van-image width="60" height="60" :src="selectEngrIcon[1]" />
            <van-icon name="arrow-down" />
          </van-col>

          <van-col span="4" offset="4" v-if="engrGroupNum == 3" @click="onClickEngr(2)">
            <van-image width="60" height="60" :src="selectEngrIcon[2]" />
            <van-icon name="arrow-down" />
          </van-col>
        </van-row>

        <van-row>
          <van-col span="4" offset="2" align="center">刻印一</van-col>
          <van-col span="4" offset="4" align="center">刻印二</van-col>
          <van-col span="4" offset="4" align="center" v-if="engrGroupNum == 3">刻印三</van-col>
        </van-row>
      </van-collapse-item>

      <!-- 权重设置 -->
      <van-collapse-item title="权重设置" name="2" v-if="affixTreeList">
        <template #title>
          <div>
            <van-icon name="cluster" />&nbsp;权重设置
          </div>
        </template>

        <van-row class="setting-btn-row">
          <van-col span="6" offset="2">
            <van-button plain type="info" size="large" icon="eye-o" @click="onSearchWeights">载入配置</van-button>
          </van-col>
          <van-col span="6" offset="1">
            <van-button plain type="info" size="large" icon="envelop-o" @click="onSaveWeights">保存配置</van-button>
          </van-col>
          <van-col span="6" offset="1">
            <van-button plain type="info" size="large" icon="share-o" @click="setAffixTreeList">恢复默认</van-button>
          </van-col>
        </van-row>

        <van-divider />

        <template>
          <van-sidebar v-model="sidebarActiveKey" class="setting-sidebar-group">
            <van-sidebar-item title="攻击类1" />
            <van-sidebar-item title="攻击类2" />
            <van-sidebar-item title="辅助类" />
            <van-sidebar-item title="防御类" />
          </van-sidebar>

          <div class="setting-sliders-div">
            <template v-for="(item, index) in affixTreeList">
              <van-row v-show="item.type == sidebarActiveKey + 1" class="border-top">

                <van-col span="6" @mouseover.native="onAffixMouseOver(item)" @mouseout.native="onAffixMouseOut">
                  <van-image height="25" width="25" :src="item.icon"></van-image>
                  <label>{{ item.name }}</label>
                </van-col>

                <!-- 滑块 -->
                <van-col span="13" offset="1" class="setting-slidercol">
                  <van-slider max="1" min="0" step="0.05" bar-height="4px" v-model="item.weight"
                    @change="onSliderChange">
                    <template #button>
                      <div class="setting-sliders-custom-button"></div>
                    </template>
                  </van-slider>
                </van-col>

                <!-- 数字框 -->
                <!-- <van-col span="7" offset="1">
                  <van-stepper v-model="item.weight" min="0" max="1" step="0.1" decimal-length="1" input-width="40px" disabled
                    button-size="20px" />
                </van-col> -->

                <!-- <van-col span="7" offset="1">
                    <input :value="item.weight">
                </van-col> -->

                <van-col offset="1">{{ item.weight }}</van-col>
              </van-row>
            </template>
          </div>
        </template>

      </van-collapse-item>
    </van-collapse>

    <!-- 结果表头 -->
    <van-divider />
    <van-row class="calc-result-title">
      <van-col offset="1" span="3">序号</van-col>
      <van-col span="16">方案</van-col>
      <van-col span="3" offset="1">评分</van-col>
    </van-row>
    <van-divider />

    <!-- 结果区域 -->
    <div class="calc-result-container">

      <!-- 筛选 -->
      <div class="calc-result-condi-container calc-result-list margin-bottom"
        v-if="calc_list && calc_list.length && calc_list.length > 0">

        <van-row>
          <van-col offset="1" span="3" class="border-left border-right border-top">&nbsp;</van-col>
          <van-col class="calc-result-list-location" span="3">I</van-col>
          <van-col class="calc-result-list-location" span="3">II</van-col>
          <van-col class="calc-result-list-location" span="3">III</van-col>
          <van-col class="calc-result-list-location" span="3">IV</van-col>
          <van-col class="calc-result-list-location" span="3">V</van-col>
          <van-col class="calc-result-list-location" span="3">VI</van-col>
          <van-col span="2" class=" border-right border-top border-bottom">&nbsp;</van-col>
        </van-row>

        <van-row>
          <van-col class="calc-result-list-indexcol border-left border-right border-bottom" offset="1" span="3">
            筛选
          </van-col>

          <van-col span="3" class="calc-result-list-imgcol">
            <el-dropdown trigger="click" @command="setConditEngrGroupView">
              <van-image width="50" :v-data="selectCondiEngrIcon[0]" height="50" :src="selectCondiEngrIcon[0]"
                :show-error="true">
                <template #error><label>点击</label><label>选择</label></template>
              </van-image>

              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="[0, { name: '', icon: '' }]"><span class="condi-any-span">任意</span>
                </el-dropdown-item>
                <el-dropdown-item v-for="viewGroup in selectCondiEngrGroupList" :command="[0, viewGroup]" divided>
                  <van-image width="50" height="50" :src="viewGroup.icon" />
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </van-col>

          <van-col span="3" class="calc-result-list-imgcol">
            <el-dropdown trigger="click" @command="setConditEngrGroupView">
              <van-image width="50" height="50" :src="selectCondiEngrIcon[1]" :show-error="true">
                <template #error><label>点击</label><label>选择</label></template>
              </van-image>

              <van-icon name="arrow-down" />
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="[1, { name: '', icon: '' }]"><span class="condi-any-span">任意</span>
                </el-dropdown-item>
                <el-dropdown-item v-for="viewGroup in selectCondiEngrGroupList" :command="[1, viewGroup]" divided>
                  <van-image width="50" height="50" :src="viewGroup.icon" />
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </van-col>

          <van-col span="3" class="calc-result-list-imgcol">
            <el-dropdown trigger="click" @command="setConditEngrGroupView">
              <van-image width="50" height="50" :src="selectCondiEngrIcon[2]" :show-error="true">
                <template #error><label>点击</label><label>选择</label></template>
              </van-image>

              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="[2, { name: '', icon: '' }]"><span class="condi-any-span">任意</span>
                </el-dropdown-item>
                <el-dropdown-item v-for="viewGroup in selectCondiEngrGroupList" :command="[2, viewGroup]" divided>
                  <van-image width="50" height="50" :src="viewGroup.icon" />
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </van-col>

          <van-col span="3" class="calc-result-list-imgcol">
            <el-dropdown trigger="click" @command="setConditEngrGroupView">
              <van-image width="50" height="50" :src="selectCondiEngrIcon[3]" :show-error="true">
                <template #error><label>点击</label><label>选择</label></template>
              </van-image>

              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="[3, { name: '', icon: '' }]"><span class="condi-any-span">任意</span>
                </el-dropdown-item>
                <el-dropdown-item v-for="viewGroup in selectCondiEngrGroupList" :command="[3, viewGroup]" divided>
                  <van-image width="50" height="50" :src="viewGroup.icon" />
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </van-col>

          <van-col span="3" class="calc-result-list-imgcol">
            <el-dropdown trigger="click" @command="setConditEngrGroupView">
              <van-image width="50" height="50" :src="selectCondiEngrIcon[4]" :show-error="true">
                <template #error><label>点击</label><label>选择</label></template>
              </van-image>

              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="[4, { name: '', icon: '' }]"><span class="condi-any-span">任意</span>
                </el-dropdown-item>
                <el-dropdown-item v-for="viewGroup in selectCondiEngrGroupList" :command="[4, viewGroup]" divided>
                  <van-image width="50" height="50" :src="viewGroup.icon" />
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </van-col>

          <van-col span="3" class="calc-result-list-imgcol">
            <el-dropdown trigger="click" @command="setConditEngrGroupView">
              <van-image width="50" height="50" :src="selectCondiEngrIcon[5]" :show-error="true">
                <template #error><label>点击</label><label>选择</label></template>
              </van-image>

              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="[5, { name: '', icon: '' }]"><span class="condi-any-span">任意</span>
                </el-dropdown-item>
                <el-dropdown-item v-for="viewGroup in selectCondiEngrGroupList" :command="[5, viewGroup]" divided>
                  <van-image width="50" height="50" :src="viewGroup.icon" />
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </van-col>

          <van-col span="2" class="calc-result-list-markcol border-bottom border-right" style="cursor:pointer"
            @click="clearConditEngrGroupView">
            <van-icon name="replay" color="red"></van-icon>
          </van-col>
        </van-row>
      </div>

      <!-- 计算结果 -->
      <template v-if="calc_list && calc_list.length && calc_list.length > 0">
        <div class="calc-result-list" v-for="(item, index) in calc_list" v-if="isShowResultRow(item)">

          <!-- 刻印位置 -->
          <van-row>
            <van-col offset="1" span="3" class="border-left border-right border-top">&nbsp;</van-col>
            <van-col class="calc-result-list-location" span="3">I</van-col>
            <van-col class="calc-result-list-location" span="3">II</van-col>
            <van-col class="calc-result-list-location" span="3">III</van-col>
            <van-col class="calc-result-list-location" span="3">IV</van-col>
            <van-col class="calc-result-list-location" span="3">V</van-col>
            <van-col class="calc-result-list-location" span="3">VI</van-col>
            <van-col span="2" class=" border-right border-top border-bottom">&nbsp;</van-col>
          </van-row>

          <!-- 刻印图片和评分 -->
          <van-row>

            <!-- 方案序号/收藏名 -->
            <van-col class="calc-result-list-indexcol border-left border-right border-bottom" offset="1" span="3">
              {{ item.name | nameSplit }}</van-col>

            <van-col span="3" class="calc-result-list-imgcol calc-result-list-0">
              <van-image :height="50" :width="50" :src="item.list[0].icon" />
            </van-col>

            <van-col span="3" class="calc-result-list-imgcol calc-result-list-1">
              <van-image :height="50" :width="50" :src="item.list[1].icon" />
            </van-col>

            <van-col span="3" class="calc-result-list-imgcol calc-result-list-2">
              <van-image :height="50" :width="50" :src="item.list[2].icon" />
            </van-col>

            <van-col span="3" class="calc-result-list-imgcol calc-result-list-3">
              <van-image :height="50" :width="50" :src="item.list[3].icon" />
            </van-col>

            <van-col span="3" class="calc-result-list-imgcol calc-result-list-4">
              <van-image :height="50" :width="50" :src="item.list[4].icon" />
            </van-col>

            <van-col span="3" class="calc-result-list-imgcol calc-result-list-5">
              <van-image :height="50" :width="50" :src="item.list[5].icon" />
            </van-col>

            <!-- 分数 -->
            <van-col span="2" class="calc-result-list-markcol border-bottom border-right"><b>{{ item.mark }}</b>
            </van-col>

          </van-row>

          <!-- 底部按钮 -->
          <van-row class="calc-result-footer">
            <van-button :icon="$options.filters.favoritedIconName(item.favorited)" plain type="danger"
              @click="onResultAddFavorite(item)" :disabled="isCalcLoading" :loading="isCalcLoading" loading-text="收藏">
              {{ item.favorited | favoriteButtonText }}</van-button>
            <van-button icon="search" plain type="info" @click="onResultView(item, index)" :disabled="isCalcLoading"
              :loading="isCalcLoading" loading-text="查看">查看</van-button>
            <van-button icon="plus" plain type="primary" @click="onAddCompare(item, index)" :disabled="isCalcLoading"
              :loading="isCalcLoading" loading-text="对比">{{ item.compared | compareButtonText }}</van-button>
          </van-row>

        </div>
      </template>
    </div>

    <!-- 底部按钮 开始按钮 -->
    <van-row class="start-button-row">
      <van-button class="first-button" v-show="startBtnShow" hairline round type="primary" 
        icon="play-circle-o" @click="onStart">开始</van-button>

      <template v-show="!startBtnShow">
        <van-button class="second-button" v-show="!startBtnShow" :loading="isCalcLoading" loading-text="计算中..." hairline round type="primary"
          icon="play-circle-o" @click="onStart">开始</van-button>

          <van-button class="second-button" v-show="!startBtnShow" :loading="isCalcLoading" loading-text="计算中..." hairline round type="danger"
          icon="revoke" @click="onReset">清空</van-button>
      </template>
    </van-row>

    <!-- 弹出层-> 选择刻印 -->
    <engr-group-view :groupViewShow="selectEngrShow" v-on:close="selectEngrShow = false"
      v-on:select="onSelecEngrtNames" />

    <!-- 弹出层-> 保存权重 -->
    <van-popup v-if="saveWeightsObject" v-model="isShowSaveWeights" closeable round position="bottom"
      style="height: 30%;">
      <van-nav-bar title="保存权重配置" />

      <van-cell-group>
        <van-field class="margin-top-more" v-model="saveWeightsObject.name" label="配置名" placeholder="输入名字" />
        <van-field class="margin-top-more" v-model="saveWeightsObject.remark" label="备注" placeholder="输入备注" />
      </van-cell-group>

      <van-row class="margin-top-more">
        <van-col span="6" offset="9">
          <van-button plain type="info" size="large" style="height:40px" icon="envelop-o" @click="onSaveWeightsCommit">
            保存配置</van-button>
        </van-col>
      </van-row>
    </van-popup>

    <!-- 查看结果弹出层 -->
    <van-popup v-model="calcResultSingleShow" round>
      <calc-result-view ref="crv" :calcResult="calcResult" :affixOptions="affixOptions" :affixList="affixList"
        v-on:crvClose="calcResultSingleShow = false" v-on:engrView="onResultViewSelectEngr">
        <template #right-btn>
          <div @click="onResultAddFavorite(calcResult)" style="color:#1989fa;">
            <van-icon :name="$options.filters.favoritedIconName(calcResult.favorited)" />&nbsp;{{ calcResult.favorited |
                favoriteButtonText
            }}
          </div>
        </template>
        <template #bottom-btn>
          <van-button icon="minus" plain type="info" @click="onResultRemove(calcResult)">移除</van-button>

          <van-button ref="crvadcbtn" icon="plus" plain type="primary" @click="onAddCompare(calcResult)">{{
              calcResult.compared | compareButtonText
          }}</van-button>

          <van-button icon="share-o" plain type="warning" @click="$refs.crv.onShare()">分享</van-button>

          <van-button icon="cluster" plain type="info" @click="onResultShowWeightsView(calcResult)">权重表</van-button>

          <van-button :icon="$options.filters.favoritedIconName(calcResult.favorited)" plain type="danger"
            @click="onResultAddFavorite(calcResult)">收藏</van-button>
        </template>
      </calc-result-view>
    </van-popup>

    <!-- 弹出层->刻印详情 -->
    <engr-view :engrViewShow="engrViewShow" :engrViewData="engrViewData" :affixOptions="affixOptions"
      :affixList="affixList" v-on:close="engrViewShow = false">
    </engr-view>

    <!-- 弹出层->收藏结果 -->
    <Favorited :isFavoritedShow="isFavoritedShow" :favoritedCalcResult="favoritedCalcResult" :affixList="affixList"
      :affixOptions="affixOptions" v-on:close="isFavoritedShow = false">
    </Favorited>

    <!-- 弹出层->查看权重表 -->
    <weights-view :isWeightsViewShow="isWeightsViewShow" :weightsResult="weightsResult" :affixList="affixList"
      :affixOptions="affixOptions" v-on:close="isWeightsViewShow = false">
    </weights-view>

    <!-- 查询权重表 -->
    <load-weights :isLoadWeightsViewShow="isLoadWeightsViewShow" v-on:close="isLoadWeightsViewShow = false"
      v-on:confirm="loadWeightsConfirm"></load-weights>

  </div>
</template>

<script>
import { CalcServer, SearchServer } from '../server/servers';
import { Toast, Notify } from 'vant';
import EngerCalc from '../server/engrCalc';
import CalcResultView from './CalcResultView';
import EngrView from './popups/EngrView';
import EngrGroupView from './popups/EngrGroupView';
import Favorited from './popups/Favorited';
import WeightsView from './popups/WeightsView';
import LoadWeights from './popups/LoadWeights';
let vm;

export default {
  name: 'Calc',
  components: { CalcResultView, EngrView, EngrGroupView, Favorited, WeightsView, LoadWeights },

  created() {
    vm = this;

    //等数据库初始化完
    setTimeout(() => {
      this.setAffixTreeList();
      this.currentWeightsId = 'default';
      this.currentWeightsName = '默认';
    }, 2000);
    // console.log("Calc.vue created", this.calc_list);
  },

  watch: {
    affixList(newval, oldval) {
      this.setAffixTreeList();
    },

    activeNames(newval, oldval) {
      this.autoTableHeight();
    },

    setGroupNumCheck1(newval, oldval) {
      this.setGroupNumCheck2 = !newval;
      if (newval) {
        this.engrGroupNum = 2;
        this.startBtnShow = true;
      }
    },

    setGroupNumCheck2(newval, oldval) {
      this.setGroupNumCheck1 = !newval;
      if (newval) {
        this.engrGroupNum = 3;
        this.startBtnShow = true;
      }
    },

    compare_list() {
      return this.$store.state.compare_list;
    },

    calc_list(val) {
      //同步到store
      this.$store.commit("syncCalceList", val);
    },

    $route(to, from) {
      if (to.path == '/Calc') {
        //本页面被激活
        /*
          页面联动 根据id检查是否被添加对比了
          如果计算结果添加收藏，再由收藏页面添加对比时 
            (因为收藏页面是该结果的克隆，导致同一结果此时存在本体和克隆对象 两个对象)
          所以calc页面每次切换显示时都要根据id判断下是否被添加了            
        */
        this.calc_list.forEach(e=>{
          if(e.compared){
            return; //等价于continue
          }

          this.compare_list.forEach(e1=>{
            if(e.id == e1.id){
              e.compared =true;
            }
          });
        });
      }
    },
  },

  computed: {
    affixList() {
      return this.$store.state.affixList;
    },

    affixOptions() {
      return this.$store.state.affixOptions;
    },

    compare_list() {
      return this.$store.state.compare_list;
    }
  },

  filters: {
    //根据 item.compared 得到按钮样式和文字
    //@TODO 在Compare页面重新设置compared后 本页面并不能自动更新  需要监听一个强制刷新事件
    compareButtonText(compared) {
      return compared ? "已加入" : "对比";
    },

    favoriteButtonText(flag) {
      return flag ? '已收藏' : '收藏';
    },

    favoritedIconName(flag) {
      return flag ? 'like' : 'like-o';
    },

    //序号列 最大3个字符
    nameSplit(val) {
      let arr = vm.chineseSplitFunction(String(val), 6)
      if (arr && arr[1]) {
        return vm.chineseSplitFunction(String(val), 4)[0] + '...'
      }

      return arr[0];
    },
  },

  data() {
    return {
      startBtnShow: true,
      calc_list: [],    //计算结果
      calcResult: null,       //操作某个结果

      activeNames: '1',
      setGroupNumCheck1: true,
      setGroupNumCheck2: false,
      engrGroupNum: 2, //单选框-两套/三套

      currentSelectEngrIndex: 0, //当前正在指定哪个刻印
      selectEngrShow: false,
      selectEngrName: ['', '', ''], //选择刻印-名字
      selectEngrIcon: ['', '', ''], //选择刻印-图标
      selectEngr: [{}, {}, {}],//选择刻印-对象

      allweights_list: [],  //查询权重表

      selectCondiEngrGroupList: [],
      selectCondiEngrIcon: ['', '', '', '', '', ''], //结果筛选
      selectCondiEngrName: ['', '', '', '', '', ''], //结果筛选

      sidebarActiveKey: "0",
      affixTreeList: null,
      affixTreeListMainIndex: 0,

      calcResultSingleShow: false,  //计算结果列表展示
      isCalcLoading: false,

      engrViewShow: false,
      engrViewData: null,

      isFavoritedShow: false,
      favoritedCalcResult: null,

      isWeightsViewShow: false,
      weightsResult: null,

      isLoadWeightsViewShow: false,

      isShowSaveWeights: false,
      saveWeightsObject: null,
      currentWeightsId: '',
      currentWeightsName: '',
    }
  },

  methods: {
    stringlenFunction: function (str) {
      var len = 0;
      for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1   
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
          len++;
        } else {
          len += 2;
        }
      }
      return len;
    },

    chineseSplitFunction(src, bytes) {
      let that = this;
      if (src == null) {
        return null;
      }
      let splitList = [];
      let startIndex = 0; // 字符串截取起始位置
      let endIndex = bytes > src.length ? src.length : bytes; // 字符串截取结束位置
      while (startIndex < src.length) {
        let subString = src.substring(startIndex, endIndex);
        // 截取的字符串的字节长度大于需要截取的长度时，说明包含中文字符
        // 获取字符串的长度，如果有中文，则每个中文字符计为2位
        while (that.stringlenFunction(subString) > bytes) {
          --endIndex;
          subString = src.substring(startIndex, endIndex);
        }
        splitList.push(src.substring(startIndex, endIndex));
        startIndex = endIndex;
        // 判断结束位置时要与字符串长度比较(src.length)，之前与字符串的bytes长度比较了，导致越界异常。
        endIndex = (startIndex + bytes) > src.length ? src.length : startIndex + bytes;
      }
      return splitList;
    },

    onReflush() {
      console.log("Calc页面刷新");
      this.$forceUpdate();
    },

    onReset() {
      this.startBtnShow = true;
      this.calc_list = [];
      this.selectEngrName = ['', '', '']
      this.selectEngrIcon = ['', '', '']
      this.selectEngr = [{}, {}, {}]
      this.activeNames = '1'
    },

    //初始化权重表
    setAffixTreeList() {
      let list = CalcServer.queryWeightsById('default');
      if (list) {
        console.log("初始化权重表", list)

        this.currentWeightsId = 'default';
        this.currentWeightsName = '默认';
        this.affixTreeList = JSON.parse(JSON.stringify(list.data));//克隆对象
        this.startBtnShow = true;
      } else {
        console.log("初始化权重表失败", list)
      }
    },

    queryAllWeightsName() {
      this.allweights_list = [];
      this.allweights_list = CalcServer.queryAllWeightsName();
    },

    //设置结果高度自适应
    autoTableHeight() {
      // this.$nextTick().then(()=>{
      //   const element =  document.getElementsByClassName('calc-result-container')[0];
      //   const startBtn = document.getElementsByClassName('start-button-row')[0];
      //   const title = document.getElementsByClassName('calc-result-title')[0];
      //   element.style.height = (startBtn.offsetTop-title.offsetTop-30)+'px';
      // })

      setTimeout(() => {
        const element = document.getElementsByClassName('calc-result-container')[0];
        const startBtn = document.getElementsByClassName('start-button-row')[0];
        const title = document.getElementsByClassName('calc-result-title')[0];
        element.style.height = (startBtn.offsetTop - title.offsetTop - 30) + 'px';
      }, 2000)
    },

    onClickEngr(index) {
      this.currentSelectEngrIndex = index;
      this.selectEngrShow = true;
    },

    //筛选列 设置赛选条件
    setConditEngrGroupView(command) {
      let index = command[0];
      let view = command[1];
      console.log("setCOnditEngrGroupView", index, view);
      this.selectCondiEngrIcon[index] = view.icon
      this.selectCondiEngrName[index] = view.name
      this.$forceUpdate();
    },

    clearConditEngrGroupView() {
      this.selectCondiEngrIcon = ['', '', '', '', '', ''];
      this.selectCondiEngrName = ['', '', '', '', '', ''];
      this.$forceUpdate();
    },

    sendWarningMsg(message) {
      Notify.clear();
      this.$nextTick().then(() => {
        Toast.fail({
          message,
          overlay: true,
          closeOnClick: true,
          closeOnClickOverlay: true,
          duration: 4000,
          position: 'top',
        });
      })
    },

    onSelecEngrtNames(item) {
      this.selectEngrShow = false;

      if (this.currentSelectEngrIndex != 0 && item.name == this.selectEngrName[0]) {
        this.sendWarningMsg('刻印不可以重复哦');
        return;
      }

      if (this.currentSelectEngrIndex != 1 && item.name == this.selectEngrName[1]) {
        this.sendWarningMsg('刻印不可以重复哦');
        return;
      }

      if (this.currentSelectEngrIndex != 2 && item.name == this.selectEngrName[2]) {
        this.sendWarningMsg('刻印不可以重复哦');
        return;
      }

      let datas = SearchServer.query({
        name: item.name
      });

      this.selectEngrName[this.currentSelectEngrIndex] = datas[0].name;
      this.selectEngrIcon[this.currentSelectEngrIndex] = datas[0].icon;
      this.selectEngr[this.currentSelectEngrIndex] = datas;
      this.startBtnShow = true;
    },

    onClickGroupNum(val) {
      this.engrGroupNum = String(val);
      console.log('this.selectEngrName', this.selectEngrName)
    },

    onSliderChange() {
      console.log("滑块移动了");
      this.currentWeightsId = "";
      this.currentWeightsName = "";
      this.startBtnShow = true;
    },

    onAffixMouseOver(item) {
      Notify.clear();
      this.$nextTick().then(() => {
        Notify({ type: 'success', message: "\n" + item.text, duration: 2000 });
      })
    },

    onAffixMouseOut() {
      // Notify.clear();
    },

    onSearchWeights() {
      console.log('Calc.vue', "onSearchWeights")
      this.isLoadWeightsViewShow = true
    },

    //应用权重表
    loadWeightsConfirm(weightsId) {
      console.log("应用权重", weightsId);
      let weights = CalcServer.queryWeightsById(weightsId);

      if (weights) {
        console.log("应用权重", weights);
        this.currentWeightsId = weights.id;
        this.currentWeightsName = weights.name
        this.affixTreeList = JSON.parse(JSON.stringify(weights.data));//克隆对象
        Notify({ type: 'success', message: "\n权重已生效", duration: 2000 });
        this.startBtnShow = true;

      } else {
        Notify({ type: 'danger', message: "\n应用失败!", duration: 2000 });
      }

      this.isLoadWeightsViewShow = false;
    },

    onSaveWeights() {
      this.saveWeightsObject = {
        name: "",
        remark: "",
        type: "custom",
        data: this.affixTreeList
      }
      this.isShowSaveWeights = true;
    },

    onSaveWeightsCommit() {
      //校验名字
      let name = this.saveWeightsObject.name;
      if (name == null || name == "") {
        return this.sendWarningMsg("配置名不能为空哦!");
      }

      CalcServer.insertWeights(this.saveWeightsObject);
      Notify({ type: 'success', message: "\n保存成功", duration: 2000 });
      this.isShowSaveWeights = false;
      this.currentWeightsId = this.saveWeightsObject.id
      this.currentWeightsName = this.saveWeightsObject.name
      this.saveWeightsObject = null;
    },

    //停止计算
    setCalcClose() {
      if (!this.isCalcLoading) {
        return;
      }

      let vm = this;
      setTimeout(() => {
        vm.isCalcLoading = false;
        // console.log(JSON.stringify(vm.calc_list));
      }, 1500);
    },

    //接收到一条结果
    setCalcResultOne(data) {
      // console.log("得到一条结果", data);
      // data  {index mark:  count: favorited:  compared:  list:[ engr ... ]}
      this.calc_list.push(data);

      //每10条排一次序
      switch (this.calc_list.length) {
        case 100: case 90: case 80: case 70: case 60:
        case 50: case 40: case 30: case 20: case 10:
          {
            //根据mark排序
            this.calc_list.sort((a, b) => {
              return b.mark - a.mark;
            })
            // this.$forceUpdate();
          }
          break;
      }
    },

    //根据筛选条件 是否隐藏一行结果
    isShowResultRow(item) {
      return item.list.every((e, i) => {
        return e.name == this.selectCondiEngrName[i] || this.selectCondiEngrName[i] == '';
      })
    },

    //开始计算
    onStart() {
      if (this.isCalcLoading) {
        return;
      }
      this.isCalcLoading = true;
      this.startBtnShow = false;

      //校验参数
      if (this.engrGroupNum != 2 && this.engrGroupNum != 3) {
        console.log("engrGroupNum", this.engrGroupNum)
        this.sendWarningMsg("参数不正确哦\n需要指定两件套或三件套");
        this.setCalcClose();
        this.startBtnShow = true;
        this.activeNames = [1];
        return
      }

      //刻印套选择 校验
      if (this.engrGroupNum == 2) {
        if (!this.selectEngr[0].length || this.selectEngr[0].length < 6
          || !this.selectEngr[1].length || this.selectEngr[1].length < 6
        ) {
          this.sendWarningMsg("参数不正确哦\n需要选定刻印~");
          this.setCalcClose();
          this.startBtnShow = true;
          this.activeNames = '1';
          // this.$forceUpdate();
          return
        }

        //设置筛选条件
        this.selectCondiEngrGroupList = [
          {
            name: this.selectEngr[0][0].name,
            icon: this.selectEngr[0][0].icon,
          },
          {
            name: this.selectEngr[1][0].name,
            icon: this.selectEngr[1][0].icon,
          },
        ]
        this.selectCondiEngrIcon = ['', '', '', '', '', ''] //结果筛选
        this.selectCondiEngrName = ['', '', '', '', '', ''] //结果筛选
      }

      if (this.engrGroupNum == 3) {
        if (!this.selectEngr[0].length || this.selectEngr[0].length < 6
          || !this.selectEngr[1].length || this.selectEngr[1].length < 6
          || !this.selectEngr[2].length || this.selectEngr[2].length < 6
        ) {

          this.sendWarningMsg("参数不正确哦\n需要选定刻印~~");
          this.activeNames = '1';
          this.setCalcClose();
          this.startBtnShow = true;
          return
        }

        this.selectCondiEngrGroupList = [
          {
            name: this.selectEngr[0][0].name,
            icon: this.selectEngr[0][0].icon,
          },
          {
            name: this.selectEngr[1][0].name,
            icon: this.selectEngr[1][0].icon,
          },
          {
            name: this.selectEngr[2][0].name,
            icon: this.selectEngr[2][0].icon,
          }
        ]
        this.selectCondiEngrIcon = ['', '', '', '', '', ''] //结果筛选
        this.selectCondiEngrName = ['', '', '', '', '', ''] //结果筛选
      }

      //权重校验
      console.log(this.affixTreeList);
      if (!this.affixTreeList) {
        this.sendWarningMsg("参数不正确哦\n需要指定权重表");
        this.activeNames = '2';
        this.setCalcClose();
        this.startBtnShow = true;
        return
      }

      if (!this.currentWeightsId) {

      }

      if (!this.currentWeightsName) {

      }

      let name = "";
      if (this.affixTreeList.some((e) => {
        name = e.name + "(" + e.weight + ")"

        if (typeof (e.weight) != 'number')
          return true

        if (e.weight < -0.001 || e.weight > 1.001)
          return true

        return false
      })) {
        this.sendWarningMsg(`参数不正确哦
${name}权重错误`);
        this.setCalcClose();
        this.activeNames = '2';
        this.startBtnShow = true;
        return
      }

      //计算过程
      this.activeNames = [];
      this.calc_list = [];
      this.$nextTick().then(() => {
        EngerCalc.calc_start(
          this.engrGroupNum,
          this.selectEngr,
          {
            weights: this.affixTreeList,
            id: this.currentWeightsId,
            name: this.currentWeightsName,
          },
          this.setCalcResultOne,
          this.setCalcClose,
          (msg) => {
            this.sendWarningMsg(msg);
            this.setCalcClose();
            this.startBtnShow = true;
          }
        )
      });
    },

    onCollapseChange(index) {
      //index 是string
      if (index == '3') {
        this.$nextTick().then(() => {
          this.activeNames = [];
          //查询收藏
        })
      }
    },

    onResultAddFavorite(item) {
      if (item.favorited) {
        //取消收藏
        let result = CalcServer.removeFavorited(item);

        if (result.code == 0) {
          item.favorited = false;
        } else {
          console.log('calc.vue', 'onResultAddFavorite', '取消收藏失败', result, item);
          Notify({ type: 'danger', message: "\n操作失败", duration: 2000 });
        }

      } else {
        //添加收藏  弹出询问框
        this.favoritedCalcResult = item;
        this.isFavoritedShow = true;
      }
    },

    //查看详情页面点击了移除
    onResultRemove(item) {
      for (let i = 0; i < this.calc_list.length; i++) {
        if (this.calc_list[i] == item) {
          this.calc_list.splice(i, 1);
          this.calcResultSingleShow = false;
          return;
        }
      }

      console.log('Calc.onResultRemove', "删除失败，未找到元素", this.calc_list);
    },

    onAddCompare(item, index) {
      if (item.compared) {
        //取消加入

        item.compared = false;
        this.$store.commit('spliceItemCompareList', item);
        
      }else{
        //加入对比
        if (!item.name) {
          item.name = '临时方案';
        }

        item.compared = true;
        this.$store.commit('pushComperList', item);

        console.log("onAddCompare commit", this.compare_list);

        Notify({ type: 'success', message: "\n添加成功" });
    
        }
    },

    onResultShowWeightsView(item) {
      console.log("Calc.vue", 'onResultShowWeightsView', item);

      if (!item.weightId || item.weightId == "") {
        Notify({ type: 'danger', message: "\n该记录没有关联权重表哦", duration: 2000 });
        return
      }

      let rs = CalcServer.queryWeightsById(item.weightId);

      if (!rs) {
        Notify({ type: 'danger', message: "\n权重表已被删除", duration: 2000 });
        return
      }

      this.weightsResult = rs;
      this.isWeightsViewShow = true;
      console.log("查看关联权重表", rs);
    },

    onResultView(item, index) {
      this.calcResult = item;
      this.$nextTick().then(() => {
        this.calcResultSingleShow = true;
      })
    },

    onResultViewSelectEngr(item) {
      this.engrViewShow = true;
      this.engrViewData = item;
    },

    queryFavorites() {
      console.log("查询我的收藏");

      let datas = CalcServer.queryAllFavorites();
      console.log("Calc.vue", "queryFavorites", datas);

      this.calc_list = datas;
      // this.$nextTick().then(() => {
      //   //等待更新完数据后 打开收藏弹出层
      // });
    },
  }
}
</script>

<style scoped>
.start-button-row {
  width: 100%;
  position: fixed;
  bottom: 70px;
  left: 0;
  right: 0;
}

.start-button-row .first-button {
  width: 90%;
  top: 10px !important;
  left: 5% !important;
  right: 0 !important;
}

.start-button-row .second-button {
  width: 45%;
  top: 10px !important;
  left: 5% !important;
  right: 0 !important;
}

.setting-btn-row button {
  height: 35px;
}

.setting-radio-group {
  height: 60px;
  position: relative;
  left: 20px;
  padding: 0;
}

.setting-radio-group .van-radio {
  height: 30px;
}

.setting-img-margintop {
  margin-top: 20px;
}

.setting-img-margintop .van-image {
  border: 1px solid rgb(210, 209, 209);
}

.setting-img-margintop .van-icon {
  position: absolute;
  clear: both;
  height: 60px;
  line-height: 60px;
  background-color: rgb(210, 209, 209);
  border: 1px solid rgb(210, 209, 209);
  border-left: none;
}

.weight-input {
  width: 40px;
}

.calc-result-title {
  color: darkgray;
  text-align: center;
  height: 15px;
  line-height: 15px;
}

.calc-result-container {
  width: 99.5%;
  height: 460px;
  overflow-x: hidden;
  overflow-y: scroll;
  /* border:1px solid red; */
}

.el-dropdown-menu .condi-any-span {
  text-align: center;
  display: inline-block;
  width: 100%;
  height: 100%;
}

.calc-result-title .van-image {
  margin-left: 10px;
}

.calc-result-title .van-col--offset-1,
.calc-result-list .van-col--offset-1 {
  margin-left: 2%;
}

.calc-result-list-location {
  text-align: center;
  border-top: 1px solid rgb(235, 237, 240);
  border-right: 1px solid rgb(235, 237, 240);
  border-bottom: 1px solid rgb(235, 237, 240);
}

.calc-result-list-imgcol {
  text-align: left;
  padding-left: 5px;
  border-right: 1px solid rgb(235, 237, 240);
  border-bottom: 1px solid rgb(235, 237, 240);
}

.calc-result-list-engrcol {
  text-align: center;
  border-right: 1px solid rgb(235, 237, 240);
  border-left: 1px solid rgb(235, 237, 240);
  border-bottom: 1px solid rgb(235, 237, 240);
}

.calc-result-list-markcol,
.calc-result-list-indexcol {
  text-align: center;
  height: 55px;
  line-height: 55px;
}

.calc-result-footer button {
  height: 30px;
  width: 20%;
  margin: 5px 0;
  margin-left: 5%;
}

.calc-result-footer button:first-child {
  margin-left: 15%;
}

.setting-sidebar-group {
  float: left;
  /* margin-top:30px; */
}

.setting-sidebar-group .van-sidebar-item {
  background-color: rgb(240, 240, 240);
}

.setting-sidebar-group .van-sidebar-item--select {
  background-color: rgb(215, 215, 215);
}

.setting-sliders-div {
  height: 300px;
  width: 385px;
  float: left;
  border: 1px solid rgb(215, 215, 215);
  overflow-y: scroll;
  overflow-x: hidden;
}

.setting-sliders-div {
  height: 238px;
}

.setting-sliders-div .van-row .van-col {
  height: 35px;
  line-height: 35px;
}

.setting-sliders-div .van-slider {
  position: relative;
  top: 40%;
  left: -10px;
}

.setting-sliders-div label {
  display: inline-block;
  position: relative;
  top: -7px;
  height: 30px;
  line-height: 30px;
}

.setting-sliders-custom-button {
  height: 15px;
  width: 15px;
  background-color: #fff;
  border-radius: 50%;
  box-shadow: 0 1px 2px rgba(0, 0, 0, .5);
}

/* CalcResultView */
.bottom-btn-container .van-button {
  margin: auto;
}

/*全局css强制覆盖*/
.wrapper /deep/ .setting-radio-group  .van-radio__label {
  margin-top: 2px;
}

.wrapper /deep/ .setting-sliders-div .van-slider__bar {
  max-width: 100%;
}

</style>

